package com.xtecher.app.okhttp;

import android.text.TextUtils;

import com.xtecher.app.utils.StringUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import okhttp3.Call;

/**
 * 封装基本的数据返回判断
 */
public class MyStringCallback extends StringCallback {
    private OnLoadListener onLoadListener;
    private String status;

    MyStringCallback(OnLoadListener onLoadListener) {
        this.onLoadListener = onLoadListener;
    }

    @Override
    public void onError(Call call, Exception e, int id) {
        onLoadListener.onFailed("请求失败");
    }

    @Override
    public void onResponse(String response, int id) {
        if (!TextUtils.isEmpty(response) && StringUtils.isJson(response)) {
            try {
                JSONObject jsonObject = new JSONObject(response);
                status = jsonObject.getString("status");
                String data = jsonObject.getString("data");
                if ("1".equals(status)&&!TextUtils.isEmpty(data)) {
                    onLoadListener.onSuccess(data);
                } else {
                    onLoadListener.onFailed("数据异常, 请稍后再试");
                }
            } catch (JSONException e) {
                e.printStackTrace();
                onLoadListener.onFailed("数据异常, 请稍后再试");
            }


        } else {
            onLoadListener.onFailed("数据异常, 请稍后再试");
        }

    }
}
